﻿using System;
using System.Collections.Generic;
using Microsoft.PlayerFramework;
using Mutzl.Samples.VideoApp.Common;
using Mutzl.Samples.VideoApp.YouTube.Model;
using Mutzl.Samples.VideoApp.YouTube.ViewModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.System.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Linq;

namespace Mutzl.Samples.VideoApp.YouTube.View
{
    public sealed partial class DetailView : LayoutAwarePage
    {
        public DetailView()
        {
            InitializeComponent();


            // Fix to enable player buttons in AppBar
            //http://playerframework.codeplex.com/wikipage?title=Applying%20Themes
            UpdateViewModel(videoPlayer.InteractiveViewModel);

            DataTransferManager.GetForCurrentView().DataRequested += DetailView_DataRequested;

        }

        void DetailView_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var video = ViewModel.Video;
            if (video == null) return;

            DataRequestDeferral deferral = args.Request.GetDeferral();

            // ToDo: C06. Sharing. Link zur App im Store anpassen. 
            // GUID gibt's erst, wenn Solution mit Store-App assoziert ist! (-> Package.StoreAssociation.xml)
            args.Request.Data.Properties.Title = "Video '" + video.Title + "'";
            var html = string.Format("<p>Hallo!</p> <p>Hier gibt's ein echt cooles Video:</p>"
                + "<p style='font-family:Arial'><strong>{0}</strong> <br/> <em>von {1}</em> </p>"
                + "<p><img alt='{0}' src='{4}' /></p>"
                + "<p>{2}</p><p>&nbsp;</p>"
                + "<p>Abrufbar entweder direkt auf <a href='{3}'>YouTube</a> oder ganz bequem mit der coolen <a href='{5}'>Video App</a> für Windows 8. </p>",
                video.Title, video.Author, video.Description, video.Link, video.ThumbNailPath,
                "http://apps.microsoft.com/webpdp/de-AT/app/my-app/00000000-0000-0000-0000-000000000000");

            args.Request.Data.SetHtmlFormat(HtmlFormatHelper.CreateHtmlFormat(html));

            deferral.Complete();

        }

        private DetailViewModel ViewModel { get { return DataContext as DetailViewModel; } }

        private void UpdateViewModel(IInteractiveViewModel vm)
        {
            ReplayButton.ViewModel = vm;
            FullScreenButton.ViewModel = vm;
            MuteButton.ViewModel = vm;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {

            var video = navigationParameter as Video;
            if (video == null)
            {
                var id = navigationParameter as string;
                if (id == null) return;
                else
                {
                    var videos = await Video.GetVideosAsync(MainViewModel.RssUri);
                    video = videos.SingleOrDefault(v => v.Id == id);
                }
            }
                
            DataContext = new DetailViewModel(video);

            ViewModel.PropertyChanged += (sender, args) =>
                {
                    if (args.PropertyName == "IsFullScreen")
                    {
                        SetVideoPlayerMode();
                    }
                };


        }

        private DisplayRequest displayRequest = null;

        protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {

            // damit der Screensaver nicht zuschlagen kann, wenn der User gerade ein Video betrachtet.
            if (displayRequest == null) displayRequest = new DisplayRequest();
            displayRequest.RequestActive();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {
            if (displayRequest != null)
            {
                displayRequest.RequestRelease();
                displayRequest = null;
            }

            DataTransferManager.GetForCurrentView().DataRequested -= DetailView_DataRequested;

            base.OnNavigatedFrom(e);
        }

        private bool IsFullScreenAllowed
        {
            get
            {
                return (ApplicationView.Value == ApplicationViewState.FullScreenLandscape
                        || ApplicationView.Value == ApplicationViewState.Filled);
            }
        }

        private void SetVideoPlayerMode()
        {
            VisualStateManager.GoToState(this, ViewModel.IsFullScreen && IsFullScreenAllowed ? "Fullscreen" : "Normal", false);

            TopAppBar.IsOpen = false;
            BottomAppBar.IsOpen = false;
        }

        protected override string DetermineVisualState(ApplicationViewState viewState)
        {
            FullScreenButton.Visibility = IsFullScreenAllowed ? Visibility.Visible : Visibility.Collapsed;
            //if (!IsFullScreenAllowed) ViewModel.IsFullScreen = false;

            SetVideoPlayerMode();


            return base.DetermineVisualState(viewState);
        }

        private void VideoPlayer_OnMediaEnded(object sender, MediaPlayerActionEventArgs e)
        {
            ViewModel.IsFullScreen = false;
        }
    }
}
